#!/bin/bash

# spring boot project start script!

APP_NAME=$1
SPRING_PROFILES_ACTIVE=$2
SERVER_PORT=$3
OPERATOR=$4

APP_PATH="../webapps/"
PID_PATH="../pid/"

usage() {
	echo "Usage: $SCRIPT [app_name] [spring_profiles_active] [server_port] [start|stop|restart|status]"
	exit 1
}

#判断是否输入了4个参数
if [ $# != 4 ]; then
	usage
fi

APP_FILE=${APP_PATH}${APP_NAME}.jar
PID_FILE=${PID_PATH}${APP_NAME}.${SERVER_PORT}.pid

#根据是否存在PID文件判定应用是否启动
is_exist() {
	if [ -f "${PID_FILE}" ]; then
		return 0
	else
		return 1
	fi
}

start() {
	is_exist
	if [ $? -eq "0" ]; then
		echo "${APP_NAME}(Port Is ${SERVER_PORT}) is already running. pid=${pid}!"
	else
		start_parameter="--spring.profiles.active=${SPRING_PROFILES_ACTIVE} --server.port=${SERVER_PORT}"
		nohup java -jar ${APP_FILE} ${start_parameter} > /dev/null 2>&1 &
		temp_pid=$!
		echo $temp_pid > $PID_FILE
		echo "${APP_NAME}(Port Is ${SERVER_PORT}) is success running, pid=${temp_pid}!"
	fi
}

stop() {
	is_exist
	if [ $? -eq "0" ]; then
		pid=`cat $PID_FILE`
		echo "pid=$pid"
		
		if [ -z "$pid" ]; then
			echo "${APP_NAME}(Port Is ${SERVER_PORT}) is not exist pid, please confirm the APP is running."
			exit 1
		fi
		
		echo "Start Stop ${APP_NAME}(Port Is ${SERVER_PORT}), PID is ${pid}!"
		
		execTime=0
		while [ {true} ]; do
			if [ $execTime -eq 0 ]; then
				kill -15 $pid
			else
				echo "Waiting ${APP_NAME}(Port Is ${SERVER_PORT}), PID is ${pid} Stopped...(${execTime}s)"
			fi

			sleep 1

			execTime=$[execTime + 1]
			tempPid=`ps aux | grep -w $pid | grep -v grep | grep -v kill | awk '{print $2}'`
			if [ -z "$tempPid" ]; then
				echo "Stopped ${APP_NAME}(Port Is ${SERVER_PORT}), Pid is ${pid}! Normal"
				rm -fr $PID_FILE
				break
			fi

			if [[ $execTime -gt 60 ]] && [[ ! -z "$tempPid" ]]; then
				echo "Stopped ${APP_NAME}(Port Is ${SERVER_PORT}), Pid is ${pid}! Force"
				kill -9 $pid
				rm -fr $PID_FILE
				break
			fi
		done
	else
		echo "${APP_NAME}(Port Is ${SERVER_PORT}) is not running"
	fi
}

status() {
  is_exist
  if [ $? -eq "0" ]; then
    echo "${APP_NAME}(Port Is ${SERVER_PORT}) is running. Pid is ${pid}!"
  else
    echo "${APP_NAME}(Port Is ${SERVER_PORT}) is not running."
  fi
}

restart() {
  stop
  start
}

case "$OPERATOR" in
	"start")
		start ;;
	"stop")
		stop ;;
	"status")
		status ;;
	"restart")
		restart ;;
	*)
		usage ;;
esac

